//
//  FZNetworkTools.swift
//  OCNetworkTools
//
//  Created by fangzhengwei on 2017/3/27.
//  Copyright © 2017年 fangzhengwei. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
enum RequestType : Int {
    case get
    case post
}

class FZNetworkTools: AFHTTPSessionManager {

    static let sharedTools : FZNetworkTools = {
        
        let tools = FZNetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
  fileprivate func loadNetData(requestType : RequestType ,urlstr : String , pramas : Any?,finishClosure : @escaping (Any? ,Error?)->()) {
        
        if requestType == .get {
            get(urlstr, parameters: pramas, progress: nil, success: { (_, response) in
                
                finishClosure(response, nil)
            }, failure: { (_, error) in
                
                finishClosure(nil, error)
            })
        }else{
            
            post(urlstr, parameters: pramas, progress: nil, success: { (_, response) in
                
                finishClosure(response, nil)
            }, failure: {  (_, error) in
                
                finishClosure(nil, error)
            })
            
        }
        
    }
}
/*获取accessToken
 client_id	true	string	申请应用时分配的AppKey。
 client_secret	true	string	申请应用时分配的AppSecret。
 grant_type	true	string	请求的类型，填写authorization_code
 code	true	string	调用authorize获得的code值。
 redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
 */

extension FZNetworkTools {
    
    func loadAccessToken(code : String ,finishClosure:@escaping ((Any?, Error?) ->())) {
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        let pramas : [String : Any] = [
            "client_id" : appKey,
            "client_secret" : appSecret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        loadNetData(requestType: .post, urlstr: urlStr, pramas: pramas, finishClosure: finishClosure)
    }
    
}


//用户信息接口 https://api.weibo.com/2/users/show.json
extension FZNetworkTools {
   
        func loadUserAccount(accessToken : String , uid : Int64,finishClosure:@escaping ((Any?, Error?) ->())) {
        
        let urlstr = "https://api.weibo.com/2/users/show.json"
        let pramas : [String : Any] = [
            "access_token" : accessToken,
            "uid" : uid
            
        ]
        
        loadNetData(requestType:.get, urlstr: urlstr, pramas: pramas, finishClosure: finishClosure)
        
    }
   
}
/*
 https://api.weibo.com/2/statuses/home_timeline.json  GET
 access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
 since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
 */

extension FZNetworkTools {
    
    func loadHomeData(accessToken : String ,maxId : Int64,sinceId : Int64, finishClouse : @escaping (Any?,Error?)->()) {
    
    let urlHome = "https://api.weibo.com/2/statuses/home_timeline.json"
    
        let pramas = ["access_token" : accessToken, "max_id" : maxId, "since_id" : sinceId] as [String : Any]
        
    loadNetData(requestType: .get, urlstr: urlHome, pramas: pramas, finishClosure: finishClouse)
        
  }
    
    
}
//access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
//status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
extension FZNetworkTools {
    
    func sendLabelBlog(accessToken : String ,status : String,finishClouse : @escaping (Any?,Error?)->()) {
        
        let sendBlog = "https://api.weibo.com/2/statuses/update.json"
        
        let pramas = ["access_token" : accessToken, "status" : status]
        
        loadNetData(requestType: .post, urlstr: sendBlog, pramas: pramas, finishClosure: finishClouse)
    }
    
    
//    https://upload.api.weibo.com/2/statuses/upload.json
//    pic	true	binary	要上传的图片，仅支持JPEG、GIF、PNG格式，图片大小小于5M。
//    UIImage *image = self.imagArr[i];
//    　　　　　　　NSData *data = UIImagePNGRepresentation(image);
//    　　　　　　　[formData appendPartWithFileData:data name:[NSString stringWithFormat:@"photos[%d]",i] fileName:[NSString stringWithFormat:@"image%d.png",i] mimeType:@"image/png"];
    
    
    func sendLabelPicsBlog(accessToken : String ,status : String,pics : [UIImage], finishClouse : @escaping (Any?,Error?)->()) {
        
        let sendBlog = "https://upload.api.weibo.com/2/statuses/upload.json"
        let pramas = ["access_token" : accessToken, "status" : status]
        
        let imgsData = NSMutableData()
        
        for image in pics{
            
             let imgData = UIImageJPEGRepresentation(image, 0.5)
            
             imgsData.append(imgData!)
        }
      post(sendBlog, parameters: pramas, constructingBodyWith: { (formData) in

      formData.appendPart(withFileData: imgsData as Data, name: "pic", fileName: "images.jpeg", mimeType: "image/jpeg")
        
      }, progress: nil, success: { (_, reponse) in
        
          finishClouse(reponse, nil)
      }) { (_, error) in
        
          finishClouse(nil, error)
     }
    
    }

}














